package org.chengn.level_middle.context670;

/**
 * @Title: Context670
 * @Author ChengN
 * @Package org.chengn.level_middle.context670
 * @Date 2024/1/22 22:34
 * @description: 最大交换
 */
public class Context670 {
    public int maximumSwap(int num) {
        final int tmp = num;
        int[] ans = new int[10];
        int idx = 0;
        while (num >= 1) {
            ans[idx++] = num % 10;
            num /= 10;
        }

        for (int i = idx - 1; i > 0; --i) {
            int maxIdx = i;
            for (int j = 0; j < i; ++j) {
                if (ans[maxIdx] < ans[j]) {
                    maxIdx = j;
                }

            }
            if (maxIdx != i) {
                ans[i] = ans[i] ^ ans[maxIdx];
                ans[maxIdx] = ans[i] ^ ans[maxIdx];
                ans[i] = ans[i] ^ ans[maxIdx];
                return combine(idx, ans);
            }
        }
        return tmp;
    }

    int combine(int idx, int[] ans) {
        int res = 0;
        for (; idx >= 0; --idx) {
            res *= 10;
            res += ans[idx];
        }
        return res;
    }
}
